export default defineNuxtRouteMiddleware((to) => {
  // A list of top-level paths that should trigger a redirect.
  const topLevelPaths = ['/singing', '/footprint'];

  // Check if the destination path is one of the top-level paths.
  if (topLevelPaths.includes(to.path)) {
    const router = useRouter();
    
    // Find all available routes.
    const allRoutes = router.getRoutes();

    // Filter for direct children of the target path that have a navTitle.
    const childRoutes = allRoutes
      .filter(r => 
        r.path.startsWith(`${to.path}/`) && 
        r.meta?.navTitle
      )
      .sort((a, b) => {
        const orderA = typeof a.meta.order === 'number' ? a.meta.order : 99;
        const orderB = typeof b.meta.order === 'number' ? b.meta.order : 99;
        return orderA - orderB;
      }); // Sort by order meta field.

    // If we found any valid child routes, redirect to the first one.
    if (childRoutes.length > 0) {
      return navigateTo(childRoutes[0].path, { redirectCode: 301 });
    }
  }
});